package com.hupu.jrs.components.okhttp

import okhttp3.*
import okio.Okio
import java.io.File
import java.io.IOException

/**
 * Created by Stark.Tony on 2018/3/18.
 */
class OkHttpHelper(private val mOkHttpClient: OkHttpClient) {

    /**
     * 该不会开启异步线程。
     *
     * @throws IOException
     */
    @Throws(IOException::class)
    fun execute(request: Request): Response {
        return mOkHttpClient.newCall(request).execute()
    }

    /**
     * 开启异步线程访问网络
     */
    fun enqueue(request: Request, responseCallback: Callback) {
        mOkHttpClient.newCall(request).enqueue(responseCallback)
    }

    /**
     * 开启异步线程访问网络, 且不在意返回结果（实现空callback）
     */
    fun enqueue(request: Request) {
        mOkHttpClient.newCall(request).enqueue(object : Callback {

            override fun onFailure(call: Call, e: IOException) {

            }

            @Throws(IOException::class)
            override fun onResponse(call: Call, response: Response) {

            }
        })
    }

    @Throws(IOException::class)
    fun getStringFromServer(url: String): String {
        val request = Request.Builder().url(url).build()
        val response = execute(request)
        return if (response.isSuccessful) {
            response.body()!!.string()
        } else {
            throw IOException("Unexpected code " + response)
        }
    }

    @Throws(Exception::class)
    fun httpDownload(url: String, target: File) {
        val request = Request.Builder().url(url).build()
        val response = mOkHttpClient.newCall(request).execute()
        if (response.isSuccessful) {
            val sink = Okio.buffer(Okio.sink(target))
            sink.writeAll(response.body()!!.source())
            sink.close()
        } else {
            throw IOException("Unexpected code " + response)
        }
    }
}
